package com.r2r.fetus;

import org.ssssssss.magicapi.Const;
import org.ssssssss.magicapi.core.service.MagicAPIService;
import org.ssssssss.magicapi.core.service.impl.DefaultMagicAPIService;
import org.tio.client.intf.TioClientHandler;
import org.tio.core.ChannelContext;
import org.tio.core.TioConfig;
import org.tio.core.exception.TioDecodeException;
import org.tio.core.intf.Packet;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

public class FetusClientHandler implements TioClientHandler {
    public  String url;
    /**
     * 解码：把接收到的ByteBuffer，解码成应用可以识别的业务消息包
     * 总的消息结构：消息头 + 消息体
     * 消息头结构：    4个字节，存储消息体的长度
     * 消息体结构：   对象的json串的byte[]
     */

    @Override
    public FetusPacket decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws TioDecodeException {
        Map<String,Object> params = new HashMap<>();
        params.put("buffer",buffer);
        return Const.getService().execute("POST","/network/socketClientDecode", params);
    }
    /**
     * 编码：把业务消息包编码为可以发送的ByteBuffer
     * 总的消息结构：消息头 + 消息体
     * 消息头结构：    4个字节，存储消息体的长度
     * 消息体结构：   对象的json串的byte[]
     */
    @Override
    public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {
        //Map<String,Object> params = new HashMap<>();
        //params.put("packet",(R2rPacket) packet);
        //R2rPacket obj = Const.getService().execute("POST","/network/socketClientEncode", params);

        byte[] body = ((FetusPacket)packet).getBody();
        int bodyLen = 0;
        if (body != null) {
        	bodyLen = body.length;
        }
        //bytebuffer的总长度是 = 消息头的长度 + 消息体的长度
        int allLen = FetusPacketV1.V1HEADER_LENGHT + bodyLen;
        //创建一个新的bytebuffer
        ByteBuffer buffer = ByteBuffer.allocate(allLen);
        //设置字节序
        buffer.order(tioConfig.getByteOrder());
        //写入消息头----消息头的内容就是消息体的长度
        buffer.putInt(bodyLen);
        //写入消息体
        if (body != null) {
        	buffer.put(body);
        }
        return buffer;
    }
    /**
     * 处理消息
     */
    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        Map<String,Object> params = new HashMap<>();
        params.put("packet",(FetusPacket) packet);
        Const.getService().execute("POST","/network/socketClientHandler", params);
    }
    /**
     * 此方法如果返回null，框架层面则不会发心跳；如果返回非null，框架层面会定时发本方法返回的消息包
     */


    @Override
    public FetusPacket heartbeatPacket(ChannelContext channelContext) {
        return null;
    }
}

